package com.xy.common.handler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.xy.common.base.entity.AjaxResult;
import com.xy.common.constant.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 配置流量sentinel控制状态异常返回数据
 */
@Component
public class UrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        AjaxResult data=null;
        if(e instanceof FlowException){
            data=AjaxResult.error(HttpStatus.CURRENT_LIMITING,"限流异常");
        }
        else if(e instanceof DegradeException){
            data=AjaxResult.error(HttpStatus.DEMOTION,"降级异常");
        }
        else if(e instanceof ParamFlowException){
            data=AjaxResult.error(HttpStatus.DEMOTION,"热点参数异常");
        }
        else if(e instanceof SystemBlockException){
            data=AjaxResult.error(HttpStatus.SYSTEM_BLOCK,"系统异常");
        }
        else if(e instanceof AuthorityException){
            data=AjaxResult.error(HttpStatus.NOT_AUTHORITY,"授权异常");
        }else {
            data=AjaxResult.error(HttpStatus.ERROR,"系统异常");
        }
        //设置json返回
        httpServletResponse.setStatus(200);
        httpServletResponse.setHeader("content-type","application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(data));
    }
}
